<?php
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
// require '/home/game37/public_html/_crawl/database.php';
// $db = new DB();

// WHERE fiximg = 0 AND image != "" AND image_up = ""

$Qry = 'SELECT g.id, g.name, g.image
		FROM games g
		WHERE fiximg = 0 AND image != "" AND image_up = ""
		ORDER BY views DESC, id DESC
		LIMIT 10';

$res = $db->fetchAll($Qry);
foreach ($res as $key=>$value) {

	$pos = strpos($value['image'], 'img.y8.com/system/screenshots');
	if ($pos !== false) {
		$url = 'http://www.y8.com/games/' . $value['name'];
		crawl($value['id'], $url);
	}
}

crawl(1, 'http://www.y8.com/games/sonic_blox');

function crawl($id, $url) {
	global $db;
	$img = '';
	$condition = 'id = ' . $id;

	$status = get_headers($url);
	if ($status[0] == 'HTTP/1.1 404 Not Found') {
		$data = array (
				'fiximg'=>1
		);
		echo $url . ' <font color="red">ERROR 404 - PAGE NOT FOUND</font><br />';
	} else {
		$html = file_get_html($url);

		if ($html->find('link[rel="image_src"]', 0)) {
			foreach ($html->find('link[rel="image_src"]') as $element) {
				$img = trim($element->href);
			}
		} else {
			foreach ($html->find('img[alt="Small"]') as $element) {
				$img = trim($element->src);
			}
		}

		if ($img) {
			$data = array (
					'image'=>$img,
					'fiximg'=>1
			);
			echo 'ID: ' . $id . ' - ' . $img . ' <font color="green">==>STATUS 200 - Updated</font><br />';
		} else {
			$data = array (
					'fiximg'=>1
			);
		}
	}
 	$db->update('games', $data, $condition);
}